# -*- coding:utf-8 -*-
from sklearn import datasets #数据集
from matplotlib import pyplot as plt
from sklearn.cross_validation import train_test_split#训练测试集划分
from sklearn import svm#支持向量机
from sklearn.externals import joblib#模型保存和加载

digits = datasets.load_digits()
#print(digits.images)#ndarray格式数据

#将数据所代表的图片显示出来
images_and_labels = list(zip(digits.images,digits.target))
#digits.target是手写数字的实际数字 ndarray格式
plt.figure(figsize = (8,6), dpi = 50)
for index,(image,label) in enumerate(images_and_labels[:8]):
    plt.subplot(2,4,index + 1)
    plt.axis('off')
    plt.imshow(image,cmap=plt.cm.gray_r,interpolation='nearest')
    plt.title('Difit:%i' % label,fontsize = 20)

'''
特征选择
根据像素点进行识别
'''
print('shape of raw image data: {0}'.format(digits.images.shape))
print('shape of data: {0}'.format(digits.data.shape))
#shape of raw image data: (1797, 8, 8)
#shape of data: (1797, 64)
#一共1797个训练样本，原始数据是8*8的图片
#使用图片的64个像素点作为特征进行训练

'''
使用支持向量机来作为手写识别算法的模型
'''
#把数据分成训练数据集和测试数据集
Xtrain,Xtest,Ytrain,Ytest = train_test_split(digits.data,digits.target,
                                             test_size = 0.2,random_state = 2)#random_state 随机数种子
#使用支持向量机来训练模型
clf = svm.SVC(gamma = 0.001,C = 100.)
clf.fit(Xtrain,Ytrain)
Ypred = clf.predict(Xtest)
#print(Ytest)

#模型测试
print('模型的准确率为{0}'.format(clf.score(Xtest,Ytest)))

#查看预测的情况
fig, axes = plt.subplots(4,4,figsize = (8,8),dpi = 50)
fig.subplots_adjust(hspace = 0.1,wspace = 0.1)#各个子图之间的间隔大小

for i ,ax in enumerate(axes.flat):
    ax.imshow(Xtest[i].reshape(8,8),cmap = plt.cm.gray_r,interpolation = 'nearest')
    ax.text(0.05,0.05,str(Ypred[i]),fontsize = 32,transform = ax.transAxes,
                          color = 'green' if Ypred[i] == Ytest[i] else 'red')
    ax.text(0.8,0.05,str(Ytest[i]),fontsize = 32,transform = ax.transAxes,color = 'black')
    ax.set_xticks([])
    ax.set_yticks([])

#保存模型参数
joblib.dump(clf,'digits_svm.pkl')
#导入模型参数
#clf = joblib.load('digits_svm.pkl')




